
#include <cstdio>
#include <cstdlib>
#include <string>

#include "SDL.h"
#include "SDL_ttf.h"

#include "ddc.h"
#include "contra_utils.h"

TTF_Font *_font = nullptr;

void _Contra_TextRenderFree() {
    if (_font != nullptr)
        TTF_CloseFont(_font);
}

void _Contra_TextRenderInit() {
    _font = TTF_OpenFont("res/font/Pixeboy-z8XGD.ttf", 30);

    if (_font == nullptr)
        printf("[Contra] Warning: Font open error: %s\n", TTF_GetError());

    std::atexit(_Contra_TextRenderFree);
}

void Contra_RenderText(int x, int y, int width, int height, std::string str) {
    if (_font == nullptr) {
        _Contra_TextRenderInit();
    }

    SDL_Surface *textSurface = TTF_RenderText_Solid(_font, str.c_str(), SDL_Color {200, 200, 200});
    if (textSurface == nullptr) {
        printf("[Contra] Warning: Text render error: %s\n", TTF_GetError());
    }

    SDL_Texture *textTexture = SDL_CreateTextureFromSurface(
                                    Dodoco::GetDodoco()->GetDodocoRenderer(),
                                    textSurface);

    SDL_Rect dstrect = SDL_Rect {x, y, width, height};

    SDL_RenderCopy(Dodoco::GetDodoco()->GetDodocoRenderer(), textTexture,
                   nullptr, &dstrect);

    SDL_FreeSurface(textSurface);
    SDL_DestroyTexture(textTexture);
}
